import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { Request, Response } from 'express';

@Catch()
export class HttpExceptionFilter extends BaseExceptionFilter {
    catch(exception: Error, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();

        let status = 500;
        if (exception instanceof HttpException) {
            status = exception.getStatus();
        }

        let message = exception.message;
        let error: Error = { name: exception.name, message, stack: exception.stack };

        response
            .status(status)
            .json(error);
    }
}